from playhouse.migrate import *
from user_module import models_sqlite as models


# 连接数据库
db_user = MySQLDatabase('db_user', user='root', password='HHup7856_@pp', host='localhost', port=3306)


class BaseModel(Model):
    class Meta:
        database = db_user


class Role(BaseModel):
    name = CharField(max_length=20, default='', unique=True)
    menus = CharField(max_length=2048, default='[]')


class User(BaseModel):
    name = CharField(max_length=10, default='')
    phone = CharField(max_length=15, index=True, default='', unique=True)
    pwd = CharField(max_length=40, index=True, default='123456')
    role = ForeignKeyField(Role, related_name='role')


class MenuInfo(BaseModel):
    # 菜单名称
    menu = CharField(max_length=10, default='')
    # 图标
    icon = CharField(max_length=50, default='')
    url = CharField(max_length=100, default='')
    # 排序依据
    # 第一个000: 父菜单, 父菜单以 '-000' 结尾
    # 第二个000: 子菜单
    sorted_index = CharField(max_length=100, default='000-000')


class GlobalData(BaseModel):
    key = CharField(max_length=128, default='', unique=True)
    value = CharField(max_length=1024, default='')


if __name__ == "__main__":

    Role.create_table()
    GlobalData.create_table()

    User.create_table()
    MenuInfo.create_table()

    my_db = PostgresqlDatabase(...)
    migrator = PostgresqlMigrator(db_user)

    try:
        migrate(migrator.add_unique('user', 'phone'))
    except BaseException as e:
        print(e)

    try:
        migrate(migrator.add_unique('role', 'name'))
    except BaseException as e:
        print(e)

    role = models.Role.select()
    for r in role:
        try:
            new_r = Role()
            new_r.name = r.name
            new_r.menus = r.menus
            new_r.save()
        except:
            pass

    user = models.User.select()
    for u in user:
        try:
            new_u = User()
            new_u.name = u.name
            new_u.phone = u.phone
            new_u.role = u.role
            new_u.pwd = u.pwd
            new_u.save()
        except:
            pass

    menu = models.MenuInfo.select()
    for m in menu:
        try:
            new_m = MenuInfo()
            new_m.menu = m.menu
            new_m.sorted_index = m.sorted_index
            new_m.url = m.url
            new_m.icon = m.icon
            new_m.save()
        except:
            pass
